/*
 * @Description: 应用全局状态
 * @Author: kanglin
 * @Date: 2018-06-06 14:17:14
 * @Copyright: Created by Panxsoft.
 */
import axios from 'axios';
import qs from 'qs';
import { Message } from 'iview';
import { parseLanguageParameter } from 'src/utils/helper';
import API_LIST from 'src/API_LIST';
/**
 *  地区语言map
 */
const LOCALE_LANGUAGE_MAP = {
	'zh-CN': '简体中文',
	'zh-TW': '繁体中文',
	'en-US': 'English',
};
/**
 * 获取当前地区
 */
const current_locale = parseLanguageParameter();


/**
 *  保存当前地区
 */
function setCurrentLocale(locale) {
	localStorage.setItem('locale', locale);
}

const state = {
	current_locale,
};

const actions = {
	/**
     * 切换语言
     * @param {*} context
     * @param {*} param1
     */
	changeLocaleAction(context, { type, id, language }) {
		const body = { type, id, language };
		if (language === 'en-US') {
			body.language = 'en';
		}
		axios.post(API_LIST.SWITCH_LANGUAGE, body)
			.then(({ data }) => {
				if (data.code !== 0) {
					throw new Error(data.error);
				} else {
					context.dispatch('menu/clearCachePageAction', null, { root: true });
					context.commit('setLocale', language);
				}
			})
			.catch((error) => {
				Message.error(error.message);
			});
	},

};


const mutations = {
	/**
     * 设置当前语言
     * @param {object} state
     * @param {string} locale
     */
	setLocale(state, locale) {
		// setLocale(locale);
		setCurrentLocale(locale);
		/* eslint-disable-next-line no-param-reassign */
		state.current_locale = locale;
		const query = qs.parse(window.location.search.replace(/^\?/, ''));
		query.lang = locale;
		window.location.href = `${window.location.pathname}?${qs.stringify(query)}${window.location.hash}`;
	},
};

const getters = {
	/**
     * 获取当前语言
     * @param {*} state
     */
	getCurrentLanguage(state) {
		const locale = state.current_locale;
		const language = LOCALE_LANGUAGE_MAP[locale];
		return language;
	},

	/**
     *  获取语言选项
     * @return {object} language options
     */
	getLanguageOptions() {
		return LOCALE_LANGUAGE_MAP;
	},
};

export default {
	namespaced: true,
	mutations,
	state,
	actions,
	getters,
};
